import { getInfo, login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import appUtils, { isBlank, isFlag } from '@/utils/util'
import { imageUtils } from '@/utils/imageUtil'

const state = {
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userName: '',
  userId: '',
  loginInfo: {},
  itemId: null,
  identifier: getToken(),
  avatorImgPath: '',
  token: getToken(),
  access: [],
  hasGetInfo: false,
  unreadCount: 0,
  uploadProgress: 0,
  messageUnreadList: [],
  messageReadedList: [],
  messageTrashList: [],
  messageContentStore: {},
  ossUploadObject: '', // 上传的图片名字
  modalPopup: {},
  reminderPopup: {},
  customerService: {},
  coverUpload: {}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_TARGET_USER: (state, user) => {
    state.user = user
  },
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  SET_USERID(state, id) {
    state.userId = id
  },
  setIdentifier(state, identifier) {
    state.identifier = identifier
  },
  setAvatar(state, avatorPath) {
    state.avatar = avatorPath
  },
  setUserName(state, name) {
    state.userName = name
  },
  setAccess(state, access) {
    state.access = access
  },
  setItemId(state, itemId) {
    state.itemId = itemId
  },
  setHasGetInfo(state, status) {
    state.hasGetInfo = status
  },
  setMessageCount(state, count) {
    state.unreadCount = count
  },
  setMessageUnreadList(state, list) {
    state.messageUnreadList = list
  },
  setMessageReadedList(state, list) {
    state.messageReadedList = list
  },
  setMessageTrashList(state, list) {
    state.messageTrashList = list
  },
  updateMessageContentStore(state, {
    msg_id,
    content
  }) {
    state.messageContentStore[msg_id] = content
  },
  moveMsg(state, {
    from,
    to,
    msg_id
  }) {
    const index = state[from].findIndex(_ => _.msg_id === msg_id)
    const msgItem = state[from].splice(index, 1)[0]
    msgItem.loading = false
    state[to].unshift(msgItem)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const {
      username,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const data = response
        if (isFlag(data.code, 0)) {
          commit('setIdentifier', '')
        } else {
          commit('SET_TOKEN', 'admin-token')
          commit('setIdentifier', data.data)
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  setRole({ commit }, roles) {
    return new Promise(resolve => {
      commit('SET_ROLES', roles)
      resolve()
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (isBlank(state.identifier)) {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        window.location.href = '#/login'
      }
      getInfo(state.identifier).then(response => {
        const data = response
        console.log(data)
        if (isFlag(data.code, 0)) {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          window.location.href = '#/login'
        } else {
          var avatar = imageUtils(appUtils.avatarImg, data.data.dataDetails.avatar)
          const accessArray = ['admin']
          commit('SET_TOKEN', state.identifier)
          commit('setIdentifier', state.identifier)
          commit('setAvatar', avatar)
          commit('setUserName', data.data.dataDetails.partnerName)
          commit('SET_USERID', data.data.dataDetails.paId)
          commit('SET_ROLES', accessArray)// 权限赋值
          setToken(state.identifier)
          resolve(data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      dispatch('tagsView/delAllCachedViews', null, { root: true })
      dispatch('tagsView/delAllVisitedViews', null, { root: true })
      dispatch('tagsView/delAllViews', null, { root: true })
      removeToken()
      resetRouter()
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      // dispatch('tagsView/delAllViews', null, {root: true})

      resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({
    commit,
    dispatch
  }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
